<?php

namespace common\behavior;

use common\model\ProjectModel;
use common\model\TaskModel;
use common\service\OrderService;
use Exception;


/**
 * reference_asset同步状态监听
 *
 * @Author meilunzhi
 */
class TaskJsonReferenceAssetUpdateAfterBehavior
{
    /**
     * 更新task reference_asset 资产数据
     *
     * @param $syncData
     *
     * @throws Exception
     */
    public function run(&$syncData)
    {
        if (empty($syncData['id'])) {
            // 同步数据id不存在
            return;
        }

        $data['json->reference_asset'] = [];
        if (!empty($syncData['json'])) {
            if (is_array($syncData['json'])) {
                // 直接走 ->sava() 方法的数据不会被 json_encode()
                $taskJson = $syncData['json'];
            } else {
                // 都modifyItem()更新的数据会走自动完成，json字段会被json_encode()
                $taskJson = json_decode($syncData['json'] ?? '', true);
            }
            // reference_asset不存在时不同步
            if(!isset($taskJson['reference_asset'])){
                return;
            }
            $data['json->reference_asset'] = $taskJson['reference_asset'];
        }

        // 取当前更新任务数据和任务所属项目的类型
        $taskInfo = model(TaskModel::class)
            ->join('project ON project.id = task.project_id', 'inner')
            ->field([
                'task.id',
                'project.type',
            ])
            ->where(['task.id' => $syncData['id']])
            ->find();

        if (empty($taskInfo['type'])) {
            return;
        }

        // 判断当前更新的任务是甲方还是乙方
        switch ($taskInfo['type']) {
            case 'insource':
                // 当前任务属于甲方
                $taskData = OrderService::getInstance()->getOutsideTaskByTaskId($taskInfo['id']);
                break;
            case 'outsource':
                // 当前任务属于乙方
                $taskData = OrderService::getInstance()->getSourceTaskByTaskId($taskInfo['id']);
                break;
            default:
                // 不属于以上类型直接返回不处理
                return;
        }

        if (empty($taskData['id'])) {
            return;
        }

        // 数据为空也同步
        model(TaskModel::class)->disableDBAfter()->where(['id' => $taskData['id']])->save($data);
    }
}
